package com.itkjb.leisurely.center.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (C), 2018-2099
 *
 * @Author: lix
 * @Date: 2019-11-29 13:24
 * @Description: 跨域配置
 * @Version: V1.0.0
 */
@Configuration
@ConditionalOnProperty(prefix = "itkjb.leisurely.center.security.cors" ,name = "open" ,havingValue = "true")
@Data
public class CorsConfig {

    @Value("#{'${itkjb.leisurely.center.security.cors.allowedOrigins}'.split(',')}")
    private List<String> allowedOrigins = new ArrayList<>();


    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 1、允许配置的域名使用
        for(String allowedOrigin: allowedOrigins){
            corsConfiguration.addAllowedOrigin(allowedOrigin);
        }

        // 2允许任何头
        corsConfiguration.addAllowedHeader("*");
        // 3允许任何方法（post、get等）
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 4
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}
